﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using GameSchool.Models;
using GameSchool.Models.Repositories;
using GameSchool.Models.Interfaces;
using GameSchool.Models.ViewModels;

namespace GameSchool.Controllers
{
    /// <summary>
    /// The NewsController handles all actions regarding newsItems - contains only CRUD actions.
    /// </summary>

    public class NewsController : Controller
    {
        //Displays the "newest" news by default - pretty much the same as the homepage
        public ActionResult Index()
        {
            //Retrive 10 news from DB
            NewsRepository rep = new NewsRepository();
            var repList = rep.GetNews().Take(10);

            //A list of the viewModel
            List<NewsItemViewModel> modelList = new List<NewsItemViewModel>();


            foreach (var n in repList)
            {
                NewsItemViewModel model = new NewsItemViewModel();
                model.date = n.DatePub;
                model.parseCourseID(n.CourseID);
                model.parseAuthorID(n.Author);
                model.ID = n.ID;
                model.Title = n.Title;
                model.Body = n.Content;
                modelList.Add(model);
            }


            return View(modelList);

        }
        
        //Returns a view allowing the user to create a new newsItem - only admins atm.
        [HttpGet]
        
         public ActionResult Create()
         {
             var db = new GameSchoolDBDataContext();
             //Generates a dropdown list of courses with their id's as values and the choice as it's name
             IEnumerable<SelectListItem> items = db.Courses
               .Select(c => new SelectListItem
               {
                   Value = c.ID.ToString(),
                   Text = c.Name
               });
             ViewBag.CourseID = items;

             return View();
            
         }
         
        public ActionResult CreateForCourse(int? ID)
        {
            var n = new NewsItem();
                n.CourseID = ID;
                n.Author = (Guid)Membership.GetUser().ProviderUserKey;
                n.DatePub = DateTime.Now;

                return View(n);
        }

        [HttpPost]
        public ActionResult CreateForCourse(NewsItem n)
        {
            var newsRep = new NewsRepository();
            newsRep.AddNews(n);
            newsRep.Save();

            return RedirectToAction("Index", "Home");
        }

        //Grabs the new newsItem from the user and adds it to the db - only admins atm.
        [HttpPost]      
         public ActionResult Create(NewsItem n)
         {
             if (n.Title.Length == 0 || n.Content.Length == 0)
                 return RedirectToAction("Create");

             var rep = new NewsRepository();
             n.Author = (Guid)Membership.GetUser().ProviderUserKey;
             n.DatePub = DateTime.Now;

            /*
             if (User.IsInRole("Admin"))//If the User is admin we have to sort the news into the Webmaster "course"
                 //The webmaster course has 1 as ID
                 n.CourseID = 1;*/
             rep.AddNews(n);
             rep.Save();
             return RedirectToAction("Index");
         }

        //Returns a view allowing the user to edit a newsIrtem - only admins atm.
         [HttpGet]
         
         public ActionResult Edit(int? ID)
         {
             if (ID.HasValue)
             {
                 NewsRepository rep = new NewsRepository();
                 var model = ( from item in rep.GetNews()
                                     where item.ID == ID
                                     select item).SingleOrDefault();

                 if (model != null)
                 {
                     //If the newsItem is found in our DB we return it to the edit view..
                     return View(model);
                 }
             }
             //If the parameter is null or the newsItem isn't found
             return View("NotFound");
         }

        //Grabs the edited newsItem from the user and updates the DB entry - only admins atm.
         [HttpPost]
         [Authorize(Roles = "Admin")]
         public ActionResult Edit(NewsItem n)
         {
             if(n.Title.Length == 0 || n.Content.Length == 0)
                 throw new ArgumentNullException("Missing title or content");

             NewsRepository rep = new NewsRepository();
             rep.EditNews(n);
             return RedirectToAction("Index");
         }
         
        //Deletes the newsItem from the DB - only admins atm.
        [Authorize(Roles = "Admin")]
         public ActionResult Delete(int? ID)
         {
             if (!ID.HasValue)
                 throw new ArgumentNullException("Delete News - null passed as argument");

             var rep = new NewsRepository();
             rep.DeleteNews(ID);
             rep.Save();
             return RedirectToAction("Index");
         }

        //To display news in edit page
        public ActionResult NewsList()
        {
            //Retrieve all news
            NewsRepository rep = new NewsRepository();
            var repList = rep.GetNews();

            //A list of the viewModel
            List<NewsItemViewModel> modelList = new List<NewsItemViewModel>();


            foreach (var n in repList)
            {
                NewsItemViewModel model = new NewsItemViewModel();
                model.date = n.DatePub;
                model.parseCourseID(n.CourseID);
                model.parseAuthorID(n.Author);
                model.ID = n.ID;
                model.Title = n.Title;
                model.Body = n.Content;
                modelList.Add(model);
            }
            return View(modelList);
        }

        //Functions for testing the controller and it's mock repo since we use a 
        //viewmodel in our real index function

        private INewsRepository m_rep = null;

        public NewsController()
        {
            m_rep = new NewsRepository();
        }

        public NewsController(INewsRepository rep)
        {
            m_rep = rep;
        }

        public ActionResult TestIndex()
        {
            var model = m_rep.GetNews().Take(10);
            return View(model);
        }
    }


}
